﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApi;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using WebApi.Model;
using WebApiExtend;
using Newtonsoft.Json;
using System.Runtime.Intrinsics.Arm;
using PddHelper.Models;
using PddHelper.Framework;
using PddHelper.Api;
using System.Drawing;
using static PddHelper.Enum;
using WebApi.Filters;

namespace WebApi.Controllers
{
    /// <summary>
    /// 登录相关 
    /// </summary>
    [ApiController]
    [Route("Login/[Action]")]
    public class LoginController : BaseController
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        public LoginController(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
        { 
        }

        #region 用户登录

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoLogin]
        public ApiResult<dynamic> Login(system_user par)
        {
            var ret = new ApiResult<dynamic>();
            var token = "";
            var msg = "登录失败,密码或用户名不正确!";
            ret.Error(msg);
             
            var user = base.DbContext<system_user>().Where(ex => ex.user_name == par.login_name && ex.password == par.password).FirstOrDefault();

            if (user != null)
            {
                #region 生成新的Token 存储到数据库中

                msg = "SUCCESS";
                var expMinute = 12 * 60;//12小时
                token = $"{user.id},{Guid.NewGuid().ToString("N")}";
                user.login_token = token;
                user.login_token_exp = DateTime.Now.AddMinutes(expMinute);
                user.login_time = DateTime.Now;

                base.DbContext<system_user>().Update(user);
                user = base.DbContext<system_user>().GetById(user.id);

                LoginCache.Dict.AddOrUpdate(user.id, user, (key, oldValue) => user);
                #endregion

                #region 返回token

                var entity = new
                {
                    userid = user.id,
                    user_name = user.user_name,
                    login_token = user.login_token,
                    login_token_exp = user.login_token_exp,
                    msg,
                };
                ret.Success(entity);

                #endregion
            }
            return ret;
        }
        #endregion

        #region 用户注册

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoLogin]
        public ApiResult<dynamic> Register(system_user par)
        {
            var ret = new ApiResult<dynamic>();
            var msg = "失败...,没事别瞎测试!";
            ret.Error(msg);

            //var obj = JsonConvert.DeserializeObject<pdd_sys_user>(par.DecDataBody); 
            var flag = true;

            //用户重复验证
            var count = DbContext<system_user>().Where(ex => ex.user_name == par.user_name).ToCount();
            if (count > 0)
            {
                flag = false;
                ret.Error("手机号存在了,请直接登录!");
            } 

            if (flag)
            {
                //赠送3小时vip 5点卡
                var entity = new system_user()
                {
                    login_name = par.login_name,
                    user_name = par.user_name,
                    password = par.password,
                    login_time = DateTime.Now
                };
                var i = DbContext<system_user>().Insert(entity);
                if (i > 0)
                {
                    ret.Success("注册成功!");
                }
            }
            return ret;
        }
        #endregion

        #region 修改密码

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult<dynamic> UpdatePwd(dynamic par)
        {
            var ret = new ApiResult<dynamic>();
            var msg = "失败...,没事别瞎测试!";
            ret.Error(msg); 

            int userid = Convert.ToInt32(par["userid"].ToString());
            var oldPwd = par["oldPwd"].ToString();
            var newPwd = par["newPwd"].ToString();

            var entity = DbContext<system_user>().Where(ex => ex.id == userid).FirstOrDefault();
            if (entity != null)
            {
                entity.password = newPwd;
                DbContext<system_user>().Update(entity);
                ret.Code = ApiStatusCode.OK;
            }
            else
            {
                ret.Code = ApiStatusCode.RequestError;
                ret.Msg = "用户不存在!";
            }
            return ret;
        }
        #endregion
    }
}
